﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Senparc.Weixin.Entities;
using Senparc.Weixin.MP.CommonAPIs;
using Senparc.Weixin.MP.Entities;

namespace MxWeiXinPF.Web.bussiness
{
    public class WxMessageFunc
    {
        public static bool SendTextMessage(string openid, string content)
        {
            if (string.IsNullOrEmpty(openid.Trim()))
            {
                return false;
            }
            Model.wx_userweixin weixin = null;
            try
            {
                weixin = ChechRegister();
            }
            catch
            {
                return false;
            }          
            WxJsonResult ret = Senparc.Weixin.MP.AdvancedAPIs.CustomApi.SendText(weixin.AppId, openid, content);
            if (ret.errcode == 0)
            {
                return true;
            }
            return false;
        }

        public static bool SendNewsMessage(string openid,string title, string content, string picurl, string url)
        {
            Model.wx_userweixin weixin = null;
            try
            {
                weixin = ChechRegister();
            }
            catch
            {
                return false;
            }
            List<Article> arcs = new List<Article>();
            Article arc = new Article();
            arc.Title = title;
            arc.PicUrl = picurl;
            arc.Url = url;
            arc.Description = content;
            arcs.Add(arc);
            WxJsonResult ret = Senparc.Weixin.MP.AdvancedAPIs.CustomApi.SendNews(weixin.AppId, openid, arcs);
            if (ret.errcode == 0)
            {
                return true;
            }
            return false;
        }

        private static Model.wx_userweixin ChechRegister()
        {
             Model.wx_userweixin weixin = new MxWeiXinPF.BLL.wx_userweixin().GetModel(Common.MyCommFun.GetMainShopID());
            if (weixin == null)
            {
                return null;
            }
            if (!AccessTokenContainer.CheckRegistered(weixin.AppId))
            {
                AccessTokenContainer.Register(weixin.AppId, weixin.AppSecret);
            }
            return weixin;
        }
    }
}